package net.sudot.chess.business.dao;

import net.sudot.chess.business.model.OrderGame;
import net.sudot.commons.pagination.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.TypedQuery;
import java.util.List;

/**
 * 游戏订单
 *
 * @author tangjialin on 2018-03-21.
 */
@Repository
public class OrderGameDao extends BaseDao<OrderGame> {

    /**
     * 获取订单列表
     *
     * @param page       分页参数
     * @param customerId 客户主键
     * @return 返回订单列表
     */
    public List<OrderGame> findList(Pageable page, Long customerId) {
        String ql = "SELECT orders FROM OrderGame orders WHERE orders.userId = :customerId ORDER BY orders.createdDate DESC";
        TypedQuery<OrderGame> query = entityManager.createQuery(ql, OrderGame.class);
        query.setParameter("customerId", customerId);
        settingPagination(query, page);
        return query.getResultList();
    }

    /**
     * 获取未完成的游戏订单信息
     *
     * @param roomId     房间主键
     * @param customerId 客户信息
     * @return 返回游戏订单信息
     */
    public OrderGame findUnComplete(Long roomId, Long customerId) {
        String ql = "SELECT orders FROM OrderGame orders WHERE orders.status = :status AND orders.target = :roomId AND orders.userId = :customerId";
        TypedQuery<OrderGame> query = entityManager.createQuery(ql, OrderGame.class);
        query.setParameter("status", OrderGame.Status.PAID);
        query.setParameter("roomId", roomId);
        query.setParameter("customerId", customerId);
        return uniqueResult(query);
    }

    /**
     * 获取未完成的游戏订单信息
     *
     * @param roomId 房间主键
     * @return 返回订单信息
     */
    public List<OrderGame> findListUnComplete(Long roomId) {
        String ql = "SELECT orders FROM OrderGame orders WHERE orders.status = :status AND orders.target = :roomId";
        TypedQuery<OrderGame> query = entityManager.createQuery(ql, OrderGame.class);
        query.setParameter("status", OrderGame.Status.PAID);
        query.setParameter("roomId", roomId);
        return query.getResultList();
    }
}
